package com.tangyee.person_risk_assessment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.tangyee.person_risk_assessment.fragment.ActionListener;
import com.tangyee.person_risk_assessment.fragment.BaseDialogFragment;
import com.tangyee.R;
import com.tangyee.person_risk_assessment.bean.OptionScoreBean;
import com.tangyee.person_risk_assessment.bean.QuestionBean;
import com.tangyee.person_risk_assessment.bean.UserAnswerStateBean;
import com.tangyee.person_risk_assessment.dao.AssessResultDAO;
import com.tangyee.person_risk_assessment.data.QuestionEntity;
import com.tangyee.person_risk_assessment.fragment.ActionListener;
import com.tangyee.person_risk_assessment.fragment.AssessFragment;
import com.tangyee.person_risk_assessment.fragment.BaseDialogFragment;
import com.tangyee.person_risk_assessment.fragment.SubmitDialog;
import com.tangyee.person_risk_assessment.fragment.UserHeightPickerDialog;
import com.tangyee.person_risk_assessment.view.AssessViewPager;

import java.util.ArrayList;
import java.util.List;

public class StartRiskAssessmentActivity extends AppCompatActivity {

    // 每个页面（viewPager）右边的翻页阴影
    private ImageView shadowView;
    // 自定义的ViewPager
    private AssessViewPager assessViewPager;
    // 左上角的返回
    private LinearLayout back;
    // 右上角提交
    private LinearLayout submit;

    // 用于实现回调
    private BaseDialogFragment heightPickerDialog;

    // 评估的问题实体(有问题与题目选项的关系，选项与分数的关系)
    private QuestionEntity questionEntity;
    // 问题与题目选项
    private List<QuestionBean> questionBeanList;
    // 选项与分数
    private List<OptionScoreBean> optionScoreBeanList;
    // 用户每一道题答题状况
    private List<UserAnswerStateBean> userAnswerStateBeanList;

    private AssessResultDAO assessResultDAO;
    private final String tableName = "AssessResult";

    public static int[] userAnswerScore;
    // 上一次评定时每一道的选项,从数据库获得，若数据库没有，则每一题都赋值为 1
    public static int[] userQuestionOption;
    // static 的初始化最好不要再 这里，因为当活动销毁时，static的变量还没那么快销毁
    // 一开始我实在这里初始化的，但我退出这个活动时，再打开这个活动时，最后一题还是以前的记录
//    public static float userQuestionHeight = -1;
//    public static float userQuestionWeight = -1;
    public static float userQuestionHeight;
    public static float userQuestionWeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start_risk_assessment);

        init();

        initAssessViewPager();
    }

    private void init(){
        shadowView = (ImageView) findViewById(R.id.shadow_view);
        assessViewPager = (AssessViewPager) findViewById(R.id.assess_viewpager);
        back = (LinearLayout)findViewById(R.id.back_assess_result);
        submit = (LinearLayout) findViewById(R.id.submit);

        heightPickerDialog = initHeightPickerDialog();
        System.out.println(heightPickerDialog);

        assessResultDAO = new AssessResultDAO(this);

        userAnswerStateBeanList = new ArrayList<>();

        questionEntity = new QuestionEntity();
        questionBeanList = questionEntity.getQuestionEntityList();
        optionScoreBeanList = questionEntity.getOptionScoreList();
        userAnswerScore = new int[questionBeanList.size()];
        // 最后一题的身高体重题没有没有记录选项，因为这个要求用户每次都得填写
        userQuestionOption = new int[questionBeanList.size()];
        // 给每一题的评定分数初始化为 -1,并且默认一个初始化一个选项
        for (int i = 0; i < questionBeanList.size(); i++) {
            userAnswerScore[i] = -1;
            userQuestionOption[i] = 1;
        }
        // 如果数据表有数据，则默认选项为上一次的评估的选项
        if(assessResultDAO.getRecordNumber(tableName) > 0){
            initOptionStateFromDataBase();
        }
        for (int i = 0; i < questionBeanList.size(); i++){
            OptionScoreBean optionScoreBean = optionScoreBeanList.get(i);
            initUserAnswerScore(optionScoreBean, i);
        }
        userQuestionWeight = -1;
        userQuestionHeight = -1;

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setSubmitListener();
            }
        });

    }

    private void initAssessViewPager() {
        assessViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                QuestionBean questionBean = questionBeanList.get(position);
                OptionScoreBean optionScoreBean = optionScoreBeanList.get(position);

                AssessFragment assessFragment =  AssessFragment.newInstance(questionBean, position, questionBeanList.size());
                assessFragment.setAssessViewPager(assessViewPager);
                assessFragment.setOptionScoreBean(optionScoreBean);

                if(position == questionBeanList.size() - 1){
                    assessFragment.setPickerDialog(new AssessFragment.NewPickerDialog() {
                        @Override
                        public void showHeightPickerDialog() {
//                            heightPickerDialog.show(getFragmentManager(), "dialog");
                            Toast.makeText(StartRiskAssessmentActivity.this, "身高", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                // 一开始是在这里初始化用户的默认的选项的分数的，但后来发现如果用户 直接点提交，
                // 没有每一页一页的翻，则没有翻的页的分数不会初始化
//                initUserAnswerScore(optionScoreBean, position);

                return assessFragment;
            }

            @Override
            public int getCount() {
                return questionBeanList.size();
            }
        });

        assessViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                shadowView.setTranslationX(assessViewPager.getWidth()-positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                System.out.println("当前处于哪页："+position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    private void initOptionStateFromDataBase(){
        int[] optionNum = assessResultDAO.getQuestionOptionNumber(tableName);
        // 以防题目的数量发生变化，但数据库没变化
        if (userQuestionOption.length == optionNum.length){
            userQuestionOption = optionNum;
        }else {
            for (int i = 0; i < optionNum.length; i++){
                userQuestionOption[i] = optionNum[i];
            }
        }
    }

    // 在这里初始化分数，主要是可能用户默认用上一次评估的结果作为这一次的结果,
    private void initUserAnswerScore(OptionScoreBean optionScoreBean, int currentNum){
        int optionNum = userQuestionOption[currentNum];
        /**
         * 评估问题的身高与体重是每一次评估都需要选择的必选项，所有最后一个问题不需要加入
         */
        if(currentNum != questionBeanList.size() - 1) {
            userAnswerScore[currentNum] = optionScoreBean.getOptionScore()[optionNum];
        }
    }

    // 点击提交的点击动作
    private void setSubmitListener(){
        // 是否每一个问题都填写了
        if(userAnswerScore[questionBeanList.size() - 1] != -1){
            for (int i = 0; i < questionBeanList.size(); i++){
                UserAnswerStateBean userAnswerStateBean = new UserAnswerStateBean();
                userAnswerStateBean.setQuestionNum(i);
                userAnswerStateBean.setQuestionOptionNum(userQuestionOption[i]);
                userAnswerStateBean.setQuestionScore(userAnswerScore[i]);
                userAnswerStateBean.setQuestionPoint(optionScoreBeanList.get(i).getQuestionPoint());
                userAnswerStateBeanList.add(userAnswerStateBean);
            }
            assessResultDAO.saveUserQuestionState(tableName, userAnswerStateBeanList);
            Toast.makeText(this, "已提交", Toast.LENGTH_SHORT).show();
            finish();
        }else { // 若没有每个问题都填写，就跳到相应的问题页
            SubmitDialog.newInstance(BaseDialogFragment.TYPE_VIEW, new ActionListener() {
                @Override
                public void onCancelClick(BaseDialogFragment dialog) {

                }

                @Override
                public void onDoneClick(BaseDialogFragment dialog) {
                    assessViewPager.setCurrentItem(questionBeanList.size() - 1);
                }
            }).show(getFragmentManager(), "view");
        }
    }

    private BaseDialogFragment initHeightPickerDialog(){
        return UserHeightPickerDialog.newInstance(UserHeightPickerDialog.TYPE_DIALOG, new ActionListener() {
            @Override
            public void onCancelClick(BaseDialogFragment dialog) {

            }

            @Override
            public void onDoneClick(BaseDialogFragment dialog) {
                Toast.makeText(StartRiskAssessmentActivity.this, "身高", Toast.LENGTH_SHORT).show();
            }
        });
    }

}
